/**
 * 登录需要验证信息
 */

//导入相应的库
import express from 'express';

//导入数据库连接
import conn from './../db/db'

import svgCaptcha from 'svg-captcha'

import config from '../src/config';

import sms_util from '../util/sms_util'




/**
 * 一次性图形验证码
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function captcha(req,res){
        // 生成随机验证码
        let captcha = svgCaptcha.create({
          color: true,
          noise: 3,
          ignoreChars: '0o1iIO',
          size: 4
      });
  
      // 保存
     req.session.captcha = captcha.text.toLocaleLowerCase();
     config.tmp_captcha = captcha.text.toLocaleLowerCase();
      // 返回客户端
      res.type('svg');
      res.send(captcha.data);
}

/**
 * 发送验证码短信
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function sendCode(req,res){
       // 获取手机号码
       let phone = req.query.phone;
       // 随机产生验证码
       let code = sms_util.randomCode(6);
       // 成功——模拟短信功能
       setTimeout(() => {
           config.users[phone] = code;
           res.json({success_code: 200, message: code});
       }, 2000);
}

/**
 * 手机验证码登录
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function loginCode(req,res){
    // 获取数据
    const phone = req.body.phone;
    const code = req.body.code;
    // 验证验证码是否正确
    if (config.users[phone] !== code) {
        res.json({err_code: 0, message: '验证码不正确!'});
    }
    // 查询数据
    delete  config.users[phone];
    let sqlStr = "SELECT * FROM user_info WHERE user_phone = '" + phone + "' LIMIT 1";
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
            res.json({err_code: 0, message: '查询失败'});
			console.log(error);
        } else {
            results = JSON.parse(JSON.stringify(results));
            if (results[0]) {  // 用户已经存在
                req.session.userId = results[0].id;
                
                res.json({
                    success_code: 200,
                    message: {
						id: results[0].id,
                        user_name: results[0].user_name,
                        user_nickname: results[0].user_nickname || '',
                        user_phone: results[0].user_phone,
						user_sex: results[0].user_sex,
						user_address: results[0].user_address,
						user_sign: results[0].user_sign,
                        user_birthday: results[0].user_birthday,
                        user_avatar: results[0].user_avatar
					}
                });
            } else { // 新用户
                const addSql = "INSERT INTO user_info(user_name, user_phone, user_avatar) VALUES (?, ?, ?)";
                const addSqlParams = [phone, phone, 'http://localhost:' + config.port + '/avatar_uploads/avatar_default.jpg'];  // 手机验证码注册，默认用手机号充当用户名
                conn.query(addSql, addSqlParams, (error, results, fields) => {
                    results = JSON.parse(JSON.stringify(results));
                    if (!error) {
                        req.session.userId = results.insertId;
                        let sqlStr = "SELECT * FROM user_info WHERE id = '" + results.insertId + "' LIMIT 1";
                        conn.query(sqlStr, (error, results, fields) => {
                            if (error) {
                                res.json({err_code: 0, message: '注册失败'});
                                console.log(error);
                            } else {
                                results = JSON.parse(JSON.stringify(results));
                                
                                res.json({
                                    success_code: 200,
                                    message: {
                                        id: results[0].id,
                                        user_name: results[0].user_name,
                                        user_phone: results[0].user_phone,
                                        user_avatar: results[0].user_avatar
                                    }
                                });
                            }
                        });
                    }
                });
            }
        }
    });
}

export default {
  captcha,
  sendCode,
  loginCode
}